package com.wxd.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxd.annotation.DataFilter;
import com.wxd.modules.sys.dao.SysUserDao;
import com.wxd.modules.sys.entity.SysDeptEntity;
import com.wxd.modules.sys.entity.SysUserEntity;
import com.wxd.modules.sys.service.SysDeptService;
import com.wxd.modules.sys.service.SysUserRoleService;
import com.wxd.modules.sys.service.SysUserService;
import com.wxd.modules.sys.shiro.ShiroUtils;
import com.wxd.utils.Constant;
import com.wxd.utils.PageUtils;
import com.wxd.utils.Query;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
     @Autowired
     private SysDeptService sysDeptService;
     @Autowired
     private SysUserRoleService sysUserRoleService;
    @Override
    @DataFilter(subDept = true,user = false)
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("username");
        String deptIdStr= (String) params.get("deptId");
        Long deptIdLong=null;
        List<Long> deptIdList = null;
        if(StringUtils.isNotBlank(deptIdStr))
        {

            deptIdLong= Long.valueOf(deptIdStr);
            deptIdList =sysDeptService.getSubDeptIdList(deptIdLong);
            deptIdList.add(deptIdLong);
        }
        IPage<SysUserEntity> page = this.page(
                new Query<SysUserEntity>().getPage(params),
                new QueryWrapper<SysUserEntity>()
                       .like(StringUtils.isNotBlank(username),"username", username).in(deptIdList!=null,"dept_id",deptIdList)
                        .apply(params.get(Constant.SQL_FILTER) != null, (String)params.get(Constant.SQL_FILTER))
        );
        for(SysUserEntity sysUserEntity:page.getRecords())
        {
            SysDeptEntity sysdeptEntity = sysDeptService.getById(sysUserEntity.getDeptId());
            sysUserEntity.setDeptName(sysdeptEntity.getName());
        }
        return new PageUtils(page);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public List<Long> queryRoleMenuId(Long roleId) {
        return baseMapper.queryRoleMenuId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUserEntity user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt= RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        user.setPassword(ShiroUtils.sha256(user.getPassword(),user.getSalt()));
        this.save(user);
        //保存用户与角色关系
        sysUserRoleService.saveOrUpDate(user.getUserId(),user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserEntity user) {
      if(StringUtils.isBlank(user.getPassword()))
      {
          user.setPassword(null);
      }
      else{
          SysUserEntity userEntity = this.getById(user.getUserId());
          user.setPassword(ShiroUtils.sha256(user.getPassword(),userEntity.getSalt()));
      }
      this.updateById(user);
      //保存用户与角色的关系
        sysUserRoleService.saveOrUpDate(user.getUserId(),user.getRoleIdList());
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity=new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id",userId).eq("password",password));
    }
}
